package org.dtree.pv.sys.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import org.dtree.pv.framework.base.service.BaseServiceImpl;
import org.dtree.pv.sys.models.Sys_menu;
import org.dtree.pv.sys.models.Sys_role;
import org.dtree.pv.sys.models.Sys_user;
import org.dtree.pv.sys.service.SysUserService;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class SysUserServiceImpl extends BaseServiceImpl<Sys_user> implements SysUserService{
    @Autowired
    public SysUserServiceImpl(Dao dao) {
        super(dao);
    }

    @Override
    public Sys_user getUserByUsername(String username){

        return dao().fetch(Sys_user.class, Cnd.where("loginname", "=", username));
    }

    @Override
    public List<Sys_role> getRolesByUsername(String username) {


        Sys_user user = getUserByUsername(username);
        dao().fetchLinks(user,"^(roles)$");
        List<Sys_role> roles = user.getRoles();
        return roles;
    }

    @Override
    public List<String> getRoleNamesByUsername(String username) {

        List<String> roles = new ArrayList<>();
        getRolesByUsername(username).forEach(role->{
            roles.add(role.getAliasName());
            System.out.println(role.getAliasName());
        });


        return roles;
    }

    @Override
    public Set<String> getPermissionByUsername(String username) {
        Set<String> roleSet = new HashSet();
        List<Sys_role> roles = getRolesByUsername(username);
        roles.forEach(role->{
            Sys_role sys_role = dao().fetchLinks(role, "^(menus)$");
            sys_role.getMenus().forEach(menu->{
                roleSet.add(menu.getPermission());
                System.out.println(menu.getPermission());
            });
        });


        return roleSet;
    }
}
